<?php

namespace app\admin\controller\shop;

use app\common\controller\Backend;
use app\common\model\Industry;
use app\common\model\Shop;
use app\common\model\ShopAudit;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 店铺审核管理
 *
 * @icon fa fa-circle-o
 */
class Audit extends Backend
{
    
    /**
     * Shop模型对象
     * @var \app\common\model\Shop
     */
    protected $model = null;
    protected $multiFields = 'status';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ShopAudit();
        $this->assign('typeList', ShopAudit::getTypeArray());
        $this->assign('statusList', ShopAudit::getStatusArray());
    }

    /**
     * 审核列表
     * @return string|\think\response\Json
     * @throws \Exception
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['user.nickname','shop_audit.phone_name','shop_audit.id', 'shop_audit.phone'], true);

//            $o_where = ['shop_audit.status' => ['neq', ShopAudit::STATUS_AUDIT_PASS]];
            $list = $this->model
                ->with('User')
//                ->where($o_where)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $curreTime = time();
            foreach($list as &$item){
                $item['industry_name'] = Industry::where('id', $item['industry_id'])->value('name') ?: '';
                if($item['status'] == ShopAudit::STATUS_AUDIT_PASS){
                    if($item['expiration_time'] <= $curreTime){
                        $item['status'] = ShopAudit::STATUS_AUDIT_EXPIRATION;
                    }
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 已认证列表
     * @return string|\think\response\Json
     * @throws \Exception
     */
    public function index_audit()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['user.nickname','shop_audit.phone_name','shop_audit.id', 'shop_audit.phone'], true);

            $o_where = ['shop_audit.status' => ShopAudit::STATUS_AUDIT_PASS];
            $list = $this->model
                ->with('User')
                ->where($o_where)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $curreTime = time();
            foreach($list as &$item){
                if($item['status'] == ShopAudit::STATUS_AUDIT_PASS){
                    if($item['expiration_time'] <= $curreTime){
                        $item['status'] = ShopAudit::STATUS_AUDIT_EXPIRATION;
                    }
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 认证未通过列表
     * @return string|\think\response\Json
     * @throws \Exception
     */
    public function index_audit_not()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['user.nickname','shop_audit.phone_name','shop_audit.id', 'shop_audit.phone'], true);

            $o_where = ['shop_audit.status' => ShopAudit::STATUS_AUDIT_REFUSE];
            $list = $this->model
                ->with('User')
                ->where($o_where)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $curreTime = time();
            foreach($list as &$item){
                if($item['status'] == ShopAudit::STATUS_AUDIT_PASS){
                    if($item['expiration_time'] <= $curreTime){
                        $item['status'] = ShopAudit::STATUS_AUDIT_EXPIRATION;
                    }
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if($this->request->isPost()) {
            $params = $this->request->param('row/a');
            $user_id = $params['user_id'];
            if($this->model->where(['user_id'=> $user_id, 'status'=>ShopAudit::STATUS_AUDIT_ING])->count()){
                $this->error("该用户已存在审核中的记录，不能添加审核");
            }
            if($this->model->where(['user_id'=> $user_id, 'status'=>ShopAudit::STATUS_AUDIT_PASS, 'expiration_time' => ['>', time()]])->count()){
                $this->error("该用户已存在未过期审核记录，不能添加审核");
            }
//            if($this->model->where(['user_id'=> $user_id])->count()){
//                $this->error("该用户已存在审核记录，不能添加审核");
//            }
        }
        return parent::add();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //当为单店的时候 、、如果当前用户认证下面有多个店铺，把此用户下除最新的店铺外，全部下架
                    if($params['type'] == ShopAudit::TYPE_SHOP_ONE){
                        //判断该用户下有多少个店铺
                        $count = Shop::where('user_id', $row->user_id)->where('is_show', Shop::IS_SHOW_YES)->count();
                        if($count > 1){
                            $new_shop_id = Shop::where('user_id', $row->user_id)->order('id desc')->value('id');
                            Shop::where('user_id', $row->user_id)->where('id', 'neq', $new_shop_id)->update(['is_show' => Shop::IS_SHOW_NOT]);
                        }
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function audit($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($this->request->isPost()){
            $status = $this->request->param('status');
            $remark = $this->request->param('remark', '');
            $expiration_time = $this->request->param('expiration_time', '');
            $saveUserData = [];
            if($status == ShopAudit::STATUS_AUDIT_PASS){
                $remark = '';
                if(empty($expiration_time)){
                    $this->error("请输入过期时间");
                }
                $expiration_time = is_numeric($expiration_time) ? $expiration_time : strtotime($expiration_time. " 23:59:59");
                if($expiration_time <= time()){
                    $this->error("过期时间不能小于当前时间");
                }
                // 2022-01-21 同步修改会员名
                $user = model('User')->get($row['user_id']);

                $saveUserData = [
                    'is_audit'  => User::IS_AUDIT_YES,
                    'audit_start_time'  => time(),
                    'shop_phone'  => $row['phone'],
                    'audit_expiration'  => $expiration_time
                ];
                if($user['nickname'] != $row['phone_name']){
                    $saveUserData['nickname'] = $row['phone_name'];
                }

            }else{
                $expiration_time = 0;
                if(empty($remark)){
                    $this->error("请输入拒绝理由");
                }
            }

            Db::startTrans();
            try{
                $row->status = $status;
                $row->audit_time = time();
                $row->expiration_time = $expiration_time;
                if($remark){
                    $row->remark = $remark;
                }
                $row->save();
                if($saveUserData){
                    //当为单店的时候 、、如果当前用户认证下面有多个店铺，把此用户下除最新的店铺外，全部下架
                    if($row['type'] == ShopAudit::TYPE_SHOP_ONE){
                        //判断该用户下有多少个店铺
                        $count = Shop::where('user_id', $user->id)->where('is_show', Shop::IS_SHOW_YES)->count();
                        if($count > 1){
                            $new_shop_id = Shop::where('user_id', $user->id)->order('id desc')->value('id');
                            Shop::where('user_id', $user->id)->where('id', 'neq', $new_shop_id)->update(['is_show' => Shop::IS_SHOW_NOT]);
                        }
                    }
                    $user->save($saveUserData);
                }
                Db::commit();
            }catch(Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success("审核成功");
        }
        $statusList = ShopAudit::getStatusArray();
        unset($statusList[ShopAudit::STATUS_AUDIT_ING]);
        $this->assign('auditStatusList', $statusList);
        return $this->view->fetch();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

}
